package tool

import java.io.File
import java.util.Locale

import scala.xml.{Node, XML}
import implicits.Implicits._
import org.joda.time.DateTime
import tool.Pojo._

import scala.concurrent.ExecutionContext.Implicits.global


/**
 * Created by yz on 12/3/2020
 */
trait ProjectTool {

  def getSampleInfoFile(dir: File) = {
    new File(dir, "sampleInfo.xlsx")
  }

  def produceBasicDatas(file: File) = {
    val xml = XML.loadFile(file)
    (xml \\ "sample").toList.map { sampleNode =>
      val id = Tool.parseGetId(sampleNode)
      val gender = (sampleNode \ "basicInfo" \ "gender").text
      val kind = (sampleNode \ "basicInfo" \ "type").text
      val lane = (sampleNode \ "basicInfo" \ "lane").text
      BasicData(id, lane, gender, kind)
    }
  }

  def parseGetId(sampleNode: Node) = {
    (sampleNode \ "basicInfo" \ "id").text
  }

  def produceStrGenotypeDataMap(xmlFile: File) = {
    val xml = XML.loadFile(xmlFile)
    (xml \\ "sample").toList.map { sampleNode =>
      val id = Tool.parseGetId(sampleNode)
      val datas = Tool.produceStrGenotypeData(sampleNode)
      (id, datas)
    }.toSeqMap
  }

  def produceStrGenotypeData(sampleNode: Node) = {
    val autoStrs = (sampleNode \\ "Autosomal_STR" \\ "autoStr").toList.map { autoNode =>
      val locus = (autoNode \ "@Locus").text
      val qc = (autoNode \\ "QC").map { node =>
        node.text
      }.mkString(";")
      val genotype = (autoNode \ "Genotypes" \\ "Genotype").toList.map(_.text).mkString(",")
      GenotypeData(locus, genotype, qc)
    }
    val yStrs = (sampleNode \\ "Y_STR" \\ "yStr").toList.map { yNode =>
      val locus = (yNode \ "@Locus").text
      val qc = (yNode \\ "QC").map { node =>
        node.text
      }.mkString(";")
      val genotype = (yNode \ "Genotypes" \\ "Genotype").toList.map(_.text).mkString(",")
      GenotypeData(locus, genotype, qc)
    }
    val xStrs = (sampleNode \\ "X_STR" \\ "xStr").toList.map { xNode =>
      val locus = (xNode \ "@Locus").text
      val qc = (xNode \\ "QC").map { node =>
        node.text
      }.mkString(";")
      val genotype = (xNode \ "Genotypes" \\ "Genotype").toList.map(_.text).mkString(",")
      GenotypeData(locus, genotype, qc)
    }
    autoStrs ::: yStrs ::: xStrs
  }

  def produceSnpGenotypeDataMap(xmlFile: File) = {
    val xml = XML.loadFile(xmlFile)
    (xml \\ "sample").toList.map { sampleNode =>
      val id = Tool.parseGetId(sampleNode)
      val datas = Tool.produceSnpGenotypeDatas(sampleNode)
      (id, datas)
    }.toMap
  }

  def produceSnpGenotypeDatas(sampleNode: Node) = {
    val id = Tool.parseGetId(sampleNode)
    (sampleNode \\ "iSNP" \\ "isnp").toList.map { snpNode =>
      val locus = (snpNode \ "@Locus").text
      val qc = (snpNode \\ "QC").map { node =>
        node.text
      }.mkString(";")
      val genotype = (snpNode \\ "Genotype").map { node =>
        node.text
      }.mkString(",")
      GenotypeData(locus, genotype, qc)
    }
  }

}
